import json

from django.shortcuts import render

# Create your views here.
from django.views import View
from django.http import JsonResponse
from hashlib import sha256
from patient.models import *
from Treats.SendMsg import *

class USER_LOGIN(View):
    def post(self, request):
        data = json.loads(request.body)
        username = data['username']
        password = data['password']
        # 对密码加密
        password_hash = sha256(password.encode('utf-8')).hexdigest()
        # 判断账号密码是否为空
        if not all([username, password]):
            return JsonResponse({'msg': '账号或者密码不能为空', 'code': 400})
        try:
            Usersview.objects.create(phone=username, pwd=password_hash)
            return JsonResponse({'msg': '注册成功', 'code': 200})
        except Exception as e:
            return JsonResponse({'msg': f'注册失败，原因是{e}', 'code': 400})


class LOGINS(View):
    def post(self, request):
        data = json.loads(request.body)
        pwd = data['password']
        pwd_hash = sha256(pwd.encode('utf-8')).hexdigest()
        pwd_com = Usersview.objects.filter(pwd=pwd_hash).first()
        if pwd_com:
            return JsonResponse({'code': 200})
        else:
            return JsonResponse({'code': 400})

class SENDCODE(View):
    def post(self, request):
        data = json.loads(request.body)
        phone = data['phone']
        code = send_code(phone)
        if code:
            return JsonResponse({'code':500,'msg':'验证码获取失败','phone_code':'code'})
        else:
            return JsonResponse({'code':200,'msg':'发送验证码成功'})

class MEDICAL(View):
    def post(self, request):
        data = json.loads(request.body)





